﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using SQLExpressDAL;
using System.Collections;
using System.Text;

public partial class Manageweb_Stock_Deal : System.Web.UI.Page
{

    SQLExpressDAL.DealRule.WebSiteConfigDataTable configTable = null;
    public string StrKey;

    protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        base.Render(htw);

        if (!hidMiYao.Value.Equals("1"))
        {
            writer.Write(sw.ToString().Replace("<body", "<body onload=javascript:openLayer('test','test_con');"));
        }
        else
        {
            writer.Write(sw);
        }
    }


    //获取密钥Cdefine5
    public string CheckData()
    {
        SqlParameter[] paras ={ 
                new SqlParameter("@userid",SqlDbType.VarChar,30)
            };
        paras[0].Value = Session["userid"];

        StrKey = SQLExpressDAL.SqlHelper.FillDataSet(CommandType.StoredProcedure, "UP_GetUserKey", paras).Tables[0].Rows[0][1].ToString();
        return StrKey;
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["UserID"] == null)
        {
            Response.Redirect("~/MemberLogin.aspx");
        }

        StrKey = CheckData();
        if (hidMiYao.Value.Equals("1"))
        {
            this.dealDiv.Visible = true;
            //交易规则信息 交易间隔 最小金额
            configTable = (SQLExpressDAL.DealRule.WebSiteConfigDataTable)Session["WebSiteConfig"];
            //GetAccountInfo();
            //if (!Page.IsPostBack)
            //{
            InitRecords();
            //初始化价格
            InitBuyPrice();
            InitMemberStockCount();
            InitMemberAccountMoney();
            //}
        }



    }

    private void InitRecords()
    {
        //初始化所有的购买记录
        BindGVBuyRecord();
        //初始化所有的卖出记录
        BindGVSaleRecord();
        //初始化购买记录的汇总
        InitGVBuySummary();
        //初始化卖出记录的汇总
        InitGVSaleSummary();
        GetOrder();
        // GetAccountInfo();
        GetUserAccountInfo();
    }

    #region  Propery

    //所持有的股票数量
    private int userStockCount;

    public int UserStockCount
    {
        get
        {
            return userStockCount;
        }

        set
        {
            userStockCount = value;
        }
    }

    //账户金额
    private Double userCurrency;

    public Double UserCurrenty
    {
        get
        {
            return Convert.ToDouble(ViewState["UserCurrency"]);
        }

        set
        {
            userCurrency = value;
            ViewState["UserCurrency"] = userCurrency;
        }
    }

    #endregion

    #region  Init  初始化方法

    private void BindGVBuyRecord()
    {
        SQLExpressDAL.DealRuleTableAdapters.DealRecordTableAdapter dealAdp = new SQLExpressDAL.DealRuleTableAdapters.DealRecordTableAdapter();
        DealRule.DealRecordDataTable dealRecordTab = dealAdp.GetAllBuyRecord();

        this.GVBuy.DataSource = dealRecordTab;
        this.GVBuy.DataBind();
    }

    private void BindGVSaleRecord()
    {
        SQLExpressDAL.DealRuleTableAdapters.DealRecordTableAdapter dealAdp = new SQLExpressDAL.DealRuleTableAdapters.DealRecordTableAdapter();
        DealRule.DealRecordDataTable dealRecordTab = dealAdp.GetAllSaleRecord();

        this.GVSale.DataSource = dealRecordTab;
        this.GVSale.DataBind();
    }

    private void InitGVBuySummary()
    {
        SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter();
        SQLExpressDAL.DealRule.DealRecordSummaryDataTable tab = adp.GetBuySummary();

        this.GVBuySummary.DataSource = tab;
        this.GVBuySummary.DataBind();
    }

    private void InitGVSaleSummary()
    {
        SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter();
        SQLExpressDAL.DealRule.DealRecordSummaryDataTable tab = adp.GetSaleSummary();

        this.GVSaleSummary.DataSource = tab;
        this.GVSaleSummary.DataBind();
    }
    //初始化购买价格
    private void InitBuyPrice()
    {
        DataRow[] drs = configTable.Select(" configname='StockDealPrice'");

        Double limitPrice = Convert.ToDouble(drs[0]["ConfigValue"]);

        drs = configTable.Select(" configname='AddValue'");
        Double addMoney = 0.0d;

        if (drs.Length != 0)
        {
            addMoney = Convert.ToDouble(drs[0]["ConfigValue"]);
        }


        string limitPriceValue = "";

        for (int i = 1; i <= 20; i++)
        {
            limitPriceValue = limitPrice.ToString("F3");
            this.ddlBuyPrice.Items.Add(new ListItem(limitPriceValue, limitPriceValue));
            this.ddlSalePrice.Items.Add(new ListItem(limitPriceValue, limitPriceValue));
            limitPrice += addMoney;
        }
    }
    //初始化卖出价格
    private void InitSalePrice()
    {
        SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter();

    }
    //获取用户所拥有的股票数量
    private void InitMemberStockCount()
    {
        SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter();
        UserStockCount = Convert.ToInt32(adp.GetUserStockCount(Session["UserID"].ToString()));
    }
    //初始化账户金额
    private void InitMemberAccountMoney()
    {
        SQLExpressDAL.Users.UsersDataTable tab = (SQLExpressDAL.Users.UsersDataTable)Session["UserInfo"];

        this.UserCurrenty = tab.Rows[0]["VCurrency"] == DBNull.Value ? 0.00d : Convert.ToDouble(tab.Rows[0]["VCurrency"]);
    }

    #endregion

    //买入股票
    protected void btnBuy_Click(object sender, EventArgs e)
    {

        //验证初次交易金额是否大于设置金额
        if (!CheckCanDeal())
        {

            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('每次交易金额最低7000才可进行交易');", true);
            return;
        }
        //是否超过账户金额
        if (!CheckAccountMoney())
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('购买失败。账户金额不足。');", true);
            //   ScriptManager.RegisterStartupScript(this.Page, this.updatePanelDeal.GetType(), "msg", "init();alert('购买失败。账户金额不足。');", true);
            return;
        }
        //是否超过总发行量
        if (!GetSaleCount())
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('购买失败,超过发行总量,不能交易!');", true);

            return;
        }

        string iid = System.Guid.NewGuid().ToString();
        //先从公司账户购买
        int flag = BuyAdminStock(iid);

        if (flag > 0)
        {
            AddBuyRecord(iid, flag);
        }

        InitRecords();
        // GetAccountInfo();
        GetUserAccountInfo();
    }
    //购买会员的股票
    private void AddBuyRecord(string guid, int buyCount)
    {

        String msg = "购买失败!";

        try
        {
            DealRecord dealObj = new DealRecord();

            String IID = guid;
            String userID = Session["UserID"].ToString();
            String stockCode = "qdzkxs";
            int count = buyCount;
            Decimal price = Convert.ToDecimal(this.ddlBuyPrice.SelectedValue);
            //0  成功 -1 失败
            int flag = dealObj.AddBuyRecord(IID, price, count, userID, stockCode);

            if (flag == 0)
            {
                msg = " 购买成功！";
            }

        }
        catch (Exception ex)
        {
            msg = "购买失败!\n" + ex.Message;
        }
        finally
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('" + msg + "');", true);

        }

    }
    //会员是否可以购买股票
    protected bool CheckCanDeal()
    {
        bool flag = false;
        try
        {

            int limitMoney = -1;

            DataRow[] drs = configTable.Select(" configname='MemAccountMoney'");

            limitMoney = Convert.ToInt32(drs[0]["configvalue"]);

            SQLExpressDAL.StockTableAdapters.UserAccountTableAdapter userAccountInfo = new SQLExpressDAL.StockTableAdapters.UserAccountTableAdapter();
            Stock.UserAccountDataTable userAccountInfoTab = userAccountInfo.GetUserAccountInfo(Session["UserID"].ToString());
            Stock.UserAccountRow row = (Stock.UserAccountRow)userAccountInfoTab.Rows[0];
            //int id = row.ID;

            Double price = Convert.ToDouble(this.ddlBuyPrice.SelectedValue);
            int count = Convert.ToInt32(this.txtBuyCount.Text.Trim());
            Double totalMoney = price * count;
            //获取以这个价格卖出的股票的数量
            SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.DealRecordSummaryTableAdapter();
            DealRule.DealRecordSummaryDataTable stockInfo = adp.GetStockCountByPrice(Convert.ToDecimal(price));
            DealRule.DealRecordSummaryRow dr = (DealRule.DealRecordSummaryRow)stockInfo.Rows[0];
            decimal currTotalValue = dr.price * dr.count;


            if (totalMoney >= limitMoney || limitMoney > currTotalValue)
            {
                flag = true;
            }

        }
        catch
        {
            flag = false;
        }
        finally
        {

        }


        return flag;
    }

    protected bool GetSaleCount()
    {
        bool flag = true;

        SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter();
        Int32 count = Convert.ToInt32(adp.GetSaleCount());

        Int32 buyCount = Convert.ToInt32(this.txtBuyCount.Text.Trim());

        if (buyCount > count)
        {
            flag = false;
        }

        return flag;

    }

    //会员是否可以卖出股票
    protected bool CheckCanSale()
    {
        bool flag = false;
        int addDay = 0;
        DataRow[] drs = configTable.Select(" configname='DealRule'");

        addDay = Convert.ToInt32(drs[0]["configvalue"]);

        SQLExpressDAL.StockTableAdapters.UserSaleTableAdapter userAccountInfo = new SQLExpressDAL.StockTableAdapters.UserSaleTableAdapter();
        Stock.UserSaleDataTable userAccountInfoTab = userAccountInfo.CheckUserCanSale(Session["UserID"].ToString());
        Stock.UserSaleRow row = (Stock.UserSaleRow)userAccountInfoTab.Rows[0];
        int id = row.salecount;
        DateTime nowDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
        DateTime buyDate = Convert.ToDateTime(row.buydate).AddDays(addDay);

        if (userAccountInfoTab.Rows.Count > 0)
        {
            if (id != 0)
            {
                flag = true;
            }
            else if (DateTime.Compare(nowDate, buyDate) > 0)
            {
                flag = true;
            }
        }

        if (!flag)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('不超过" + addDay.ToString() + "天不能出售.');", true);
        }


        return flag;
    }
    //购买金额是否超过账户金额
    protected bool CheckAccountMoney()
    {
        bool flag = false;

        Double price = Convert.ToDouble(this.ddlBuyPrice.SelectedValue);
        Double count = Convert.ToDouble(this.txtBuyCount.Text.Trim());
        decimal totalMoney = (decimal)(price * count);

        GetUserAccountInfo();
        decimal userAccount = (decimal)UserCurrenty;
        if (totalMoney <= userAccount)
        {
            flag = true;
        }

        return flag;
    }

    protected void btnSale_Click(object sender, EventArgs e)
    {

        if (!CheckSaleCount())
        {
            return;
        }

        if (!CheckSaleCountPercent())
        {
            return;
        }

        if (!CheckCanSale())
        {
            return;
        }

        AddSaleRecord();
        InitRecords();
        //  GetAccountInfo();
        GetUserAccountInfo();
    }

    //验证卖出数量是否超过拥有的数量
    protected bool CheckSaleCount()
    {
        bool flag = false;

        int buyCount = Convert.ToInt32(this.txtSaleCount.Text.Trim());
        GetUserStockSummary();
        Label lblLiuTong = Master.FindControl("lblLiuTongCount") as Label;
        InitMemberStockCount();

        //if (buyCount <= UserStockCount)
        if (buyCount <= Convert.ToInt32(lblLiuTong.Text))
        {
            flag = true;
        }

        if (!flag)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('卖出失败.\\n卖出数量超过流通数量.');", true);
        }

        return flag;
    }

    //检查卖出数量所占总数的百分比
    protected bool CheckSaleCountPercent()
    {
        bool flag = false;

        SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter dealRule = new SQLExpressDAL.DealRuleTableAdapters.UserSaleRuleTableAdapter();
        int count = (int)dealRule.GetUserStockCount(Session["userid"].ToString());

        if (count == 0)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('你还没有购买任何股票\n您所购买的股票还未完成交易.');", true);
            return flag;

        }

        if (count > 0 && (Convert.ToInt64(this.txtSaleCount.Text.Trim()) / count <= 0.7))
        {
            flag = true;
            return flag;
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('你还没有购买任何股票\n您所购买的股票还未完成交易.');", true);
            return flag;
        }



    }
    //会员卖出股票
    private void AddSaleRecord()
    {
        String msg = "卖出失败!";

        try
        {
            DealRecord dealObj = new DealRecord();

            String IID = System.Guid.NewGuid().ToString();
            String userID = Session["UserID"].ToString();
            String stockCode = "qdzkxs";
            int count = Convert.ToInt32(this.txtSaleCount.Text.Trim());
            Decimal price = Convert.ToDecimal(this.ddlSalePrice.SelectedValue);

            int flag = dealObj.AddSaleRecord(IID, price, count, userID, stockCode);

            if (flag == 0)
            {
                msg = "卖出成功";
            }
        }
        catch (Exception ex)
        {
            msg = "卖出失败!\n" + ex.Message;
        }
        finally
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('" + msg + "');", true);

        }


    }

    /// <summary>
    /// 购买公司的股票
    /// </summary>
    /// <param name="guid">交易单号</param>
    /// <returns>未交易的数量 (0 全部交易 大于零代表还需要购买的数量)</returns>
    private int BuyAdminStock(string guid)
    {
        int IsCanContinue = -1;
        string msg = "购买成功";
        try
        {
            DealRecord dealObj = new DealRecord();

            String IID = guid;
            String userID = Session["UserID"].ToString();
            String stockCode = "qdzkxs";
            int count = Convert.ToInt32(this.txtBuyCount.Text.Trim());
            Decimal price = Convert.ToDecimal(this.ddlBuyPrice.SelectedValue);

            System.Collections.Hashtable htab = dealObj.BuyAdminRecord(IID, price, count, userID, stockCode);

            int flag = Convert.ToInt16(htab["IsSuccess"]);
            int unDealCount = Convert.ToInt32(htab["Count"]);

            if (flag == 0)
            {
                if (unDealCount > 0)
                {
                    IsCanContinue = unDealCount;
                }
            }
            else
            {
                msg = "购买失败";
            }
        }
        catch (Exception ex)
        {

            msg = "购买失败\n" + ex.Message;
        }

        if (IsCanContinue == -1)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('" + msg + "!');", true);
        }

        return IsCanContinue;
    }

    #region Event
    protected void GVBuySummary_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "saleClick('" + e.Row.Cells[1].Text + "')");
        }
    }

    protected void GVSaleSummary_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "buyClick('" + e.Row.Cells[1].Text + "')");
        }
    }
    #endregion

    #region  取消订单

    protected void GVOrderState_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GVOrderState.PageIndex = e.NewPageIndex;
        GetOrder();
    }

    private void GetOrder()
    {
        SQLExpressDAL.DealRuleTableAdapters.OrderStateTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.OrderStateTableAdapter();
        SQLExpressDAL.DealRule.OrderStateDataTable tab = adp.GetOrderState(Session["userid"].ToString());

        this.GVOrderState.DataSource = tab;
        this.GVOrderState.DataBind();
    }

    protected void lbtnCancel_Command(object sender, CommandEventArgs e)
    {
        string msg = "操作成功！";
        try
        {
            int orderID = Convert.ToInt16(e.CommandArgument);

            SQLExpressDAL.DealRuleTableAdapters.OrderStateTableAdapter adp = new SQLExpressDAL.DealRuleTableAdapters.OrderStateTableAdapter();
            int flag = adp.CancelOrderByID(orderID);
            msg = flag > 0 ? "操作成功！" : "操作失败！";
        }
        catch
        {
            msg = "操作失败！";
        }
        finally
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "init();alert('" + msg + "');", true);
            InitRecords();
        }


    }

    #endregion


    //计算重新显示账户金额 
    public void GetAccountInfo()
    {
        SQLExpressDAL.UsersTableAdapters.UsersTableAdapter userAdp = new SQLExpressDAL.UsersTableAdapters.UsersTableAdapter();
        SQLExpressDAL.Users.UsersDataTable tab = userAdp.GetSingleUserInfo(Session["UserID"].ToString());

        DataRow dr = tab.Rows[0];


        //Label lblUserName = Master.FindControl("lblUserName") as Label;

        //Label lblAccount = Master.FindControl("lblAccount") as Label;


        SQLExpressDAL.DealRecord obj = new SQLExpressDAL.DealRecord();
        Hashtable htab = obj.GetMemAccountMoney(Session["UserID"].ToString());

        if (htab["IsSuccess"].ToString().Equals("1"))
        {
            //Label lblAccountMoney = Master.FindControl("lblAccountMoney") as Label;

            //lblAccountMoney.Text = htab["Count"].ToString();
            //UserCurrenty = Convert.ToDouble(lblAccountMoney.Text);
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('金额统计错误');", true);
            return;
        }


        Label LjScore = Master.FindControl("lblLjScore") as Label;
        LjScore.Text = dr["ljscore"].ToString();
        Label SpecialScore = Master.FindControl("lblSpecialScore") as Label;
        SpecialScore.Text = dr["specialscore"].ToString();

    }


    /// <summary>
    /// 初始化账户的金额信息(左侧列表)
    /// </summary>
    protected void GetUserAccountInfo()
    {
        SQLExpressDAL.TransferRecordsTableAdapters.UsersAccountTableAdapter adp = new SQLExpressDAL.TransferRecordsTableAdapters.UsersAccountTableAdapter();
        SQLExpressDAL.TransferRecords.UsersAccountDataTable tab = adp.GetSingleAccount(Session["UserID"].ToString());

        SQLExpressDAL.TransferRecords.UsersAccountRow dr = (SQLExpressDAL.TransferRecords.UsersAccountRow)tab.Rows[0];

        Label lblAB1 = Master.FindControl("lblAB1") as Label;

        Label lblAB2 = Master.FindControl("lblAB2") as Label;

        Label lblAB3 = Master.FindControl("lblAB3") as Label;

        Label lblAB4 = Master.FindControl("lblAB4") as Label;

        lblAB1.Text = dr.AB1.ToString("f2");
        lblAB2.Text = dr.AB2.ToString("f2");
        lblAB3.Text = dr.AB3.ToString("f2");
        UserCurrenty = Convert.ToDouble(lblAB3.Text);
        lblAB4.Text = dr.AB4.ToString("f2");
    }

    protected void GetUserStockSummary()
    {
        string msg = "";
        try
        {
            SQLExpressDAL.DealRecord obj = new SQLExpressDAL.DealRecord();
            DataTable tab = obj.GetUserStockSummary(Session["UserID"].ToString());


            if (tab.Rows.Count > 0)
            {
                int isSuccess = Convert.ToInt32(tab.Rows[0]["Success"]);

                if (isSuccess == 0)
                {
                    DataRow dr = tab.Rows[0];

                    Int32 closeCount = Convert.ToInt32(dr["closeCount"]);
                    Int32 circulateCount = Convert.ToInt32(dr["circulateCount"]);
                    Int32 salingCount = Convert.ToInt32(dr["salingCount"]);
                    Double price = Convert.ToDouble(dr["price"]);

                    Label lblLiuTong = Master.FindControl("lblLiuTongCount") as Label;
                    Label lblCloseCount = Master.FindControl("lblCloseCount") as Label;
                    Label lblSalingCount = Master.FindControl("lblSalingCount") as Label;
                    Label lblTotalCount = Master.FindControl("lblTotalCount") as Label;
                    Label lblTotalMoney = Master.FindControl("lblTotalMoney") as Label;


                    lblLiuTong.Text = circulateCount.ToString();
                    lblCloseCount.Text = closeCount.ToString();
                    lblSalingCount.Text = salingCount.ToString();
                    lblTotalCount.Text = (closeCount + circulateCount + salingCount).ToString();
                    lblTotalMoney.Text = (closeCount * price + circulateCount * price + salingCount * price).ToString();
                }
                else
                {
                    msg = "股权摘要查询出错!";
                }

            }
            else
            {
                msg = "股权摘要查询出错!";
            }
        }
        catch (Exception ex)
        {
            msg = ex.Message.ToString();
        }
        finally
        {
            if (!string.IsNullOrEmpty(msg))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('" + msg + "');", true);
            }
        }

    }

}


